package org.colcon.web.client;

import org.colcon.web.client.ui.BodyPanel;
import org.colcon.web.client.ui.HeaderPanel;
import org.colcon.web.client.ui.MainPanel;
import org.colcon.web.model.User;
import org.colcon.web.model.framework.IUser;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

public class Collective_Congress implements EntryPoint 
{
	private final ColConServiceAsync service = 
			GWT.create(ColConService.class);
	
	private IUser user;
	
	private MainPanel mainPanel;

	public void onModuleLoad()
	{
		user = null;
		
		refresh();
	}
	
	public void refresh()
	{
		RootPanel.get().clear();	
		mainPanel = new MainPanel(this);
		RootPanel.get().add(mainPanel);
	}
	
	public void refreshUser()
	{
		if(!loggedIn())
			return;
		
		getService().getUser(user.getId(), new AsyncCallback<User>()
		{
			public void onFailure(Throwable caught)
			{
				System.err.println("Failed to refresh user " + user.getId());
				logout();
				refresh();
			}
			
			public void onSuccess(User user)
			{
				login(user);
				refresh();
			}
		});
	}
	
	public boolean loggedIn()
	{
		return user != null;
	}
	
	public IUser getUser()
	{
		return user;
	}
	
	public void login(IUser user)
	{
		this.user = user;
	}
	
	public void logout()
	{
		user = null;
	}
	
	public ColConServiceAsync getService()
	{
		return service;
	}
	
	public MainPanel getMainPanel()
	{
		return mainPanel;
	}
	
	public HeaderPanel getHeaderPanel()
	{
		return getMainPanel().getHeaderPanel();
	}
	
	public BodyPanel getBodyPanel()
	{
		return getMainPanel().getBodyPanel();
	}
}
